<template>
  <div class="content">
    <div class="contain">
      <el-container class="outer">
        <!--左侧-->
        <el-aside>
          <div class="platform">自动化测试平台<br>
            <span>-- tgl</span>
          </div>
          <!--导航栏-->
          <el-menu :default-active="$route.path" unique-opened router>
            <hr>
            <el-menu-item index="/home" :key="0">
              <i class="el-icon-menu"></i>
              <span slot="title">首页</span>
            </el-menu-item>
            <!--一级菜单-->
            <!--index只接收字符串-->
            <el-submenu :index="item.path" v-for="item in navList" :key="item.id">
              <template slot="title">
                <i :class="item.icon"></i>
                <span>{{ item.name }}</span>
              </template>
              <!--二级菜单-->
              <el-menu-item :index="child.path" v-for="child in item.children" :key="child.id">
                <template slot="title">
                  <i :class="child.icon"></i>
                  <span>{{ child.name }}</span>
                </template>
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </el-aside>
        <!--右侧-->
        <el-container>
          <!--顶部-->
          <el-header>
            <el-dropdown split-button size="small">
              <span class="el-dropdown-link">{{ username }}</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="openUserInfoDialog">个人信息</el-dropdown-item>
                <el-dropdown-item @click.native="openPasswordDialog">修改密码</el-dropdown-item>
                <el-dropdown-item @click.native="userLogout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-header>
          <!--右侧主体区-->
          <el-main>
            <!--路由占位符-->
            <router-view></router-view>
          </el-main>
        </el-container>
      </el-container>
    </div>
    <!--用户信息对话框-->
    <el-dialog title="用户信息" :visible.sync="userDialogVisible" width="30%" :append-to-body="true"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="userDialogClose">
      <!--用户信息表单-->
      <el-form :model="editUserForm" status-icon :rules="editUserRule" ref="editUserRef" label-width="90px">
        <el-form-item label="账号" prop="username" label-width="60px">
          <el-input prefix-icon="el-icon-user" v-model="editUserForm.username" placeholder="请输入账号" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="is_superuser" label-width="60px">
          <el-input prefix-icon="el-icon-user" v-model="editUserForm.is_superuser" placeholder="请选择角色" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" label-width="60px">
          <el-input prefix-icon="el-icon-collection-tag" v-model="editUserForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="60px">
          <el-input prefix-icon="el-icon-message" v-model="editUserForm.email"
                    placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone" label-width="60px" class="phone">
          <el-input prefix-icon="el-icon-mobile-phone" v-model="editUserForm.phone"
                    placeholder="请输入手机号码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogCancelClose">取 消</el-button>
        <el-button type="primary" @click="editThisUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改密码对话框-->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="30%" :append-to-body="true"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="passwordDialogClose">
      <!--用户信息表单-->
      <el-form :model="editPasswordForm" status-icon :rules="editPasswordRule" ref="editPasswordRef" label-width="90px">
        <el-form-item label="旧密码" prop="old_password" label-width="65px">
          <el-input type="password" prefix-icon="el-icon-lock" v-model="editPasswordForm.old_password"
                    placeholder="请输入旧密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_password" label-width="65px">
          <el-input type="password" prefix-icon="el-icon-lock" v-model="editPasswordForm.new_password"
                    placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogCancelClose">取 消</el-button>
        <el-button type="primary" @click="editPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getNavs, getUserInfo, editUserInfo, editUserPassword } from '../api/api'
import CryptoJS from 'crypto-js'

export default {
  created: function () {
    this.username = window.sessionStorage.getItem('username')
    this.getNavList()
  },
  data () {
    // var checkEmail = (rule, value, callback) => {
    //   if (value) {
    //     repeatEmail(value).then(response => {
    //       if (response.data.code === 0) {
    //         callback()
    //       } else if (response.data.code === 1 && response.data.message.id === this.userId) {
    //         callback()
    //       } else {
    //         callback(new Error(response.data.message.email))
    //       }
    //     })
    //   }
    // }
    // const checkUsername = (rule, value, callback) => {
    //   if (value) {
    //     repeatUsername(value).then(response => {
    //       if (response.data.code === 0) {
    //         callback()
    //       } else if (response.data.code === 1 && response.data.message.id === this.userId) {
    //         callback()
    //       } else {
    //         callback(new Error(response.data.message.username))
    //       }
    //     })
    //   }
    // }
    const checkOldPassword = (rule, value, callback) => {
      if (value) {
        this.checkPassword = CryptoJS.AES.decrypt(
          window.sessionStorage.getItem('pwd'),
          CryptoJS.enc.Utf8.parse(window.sessionStorage.getItem('key')),
          { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString(CryptoJS.enc.Utf8)
        if (this.checkPassword !== value) {
          callback(new Error('旧密码错误！'))
        }
        callback()
      }
    }
    return {
      checkPassword: '',
      username: '',
      navList: [],
      userId: '',
      userEmail: '',
      userDialogVisible: false,
      editUserForm: {},
      editUserRule: {
        // username: [
        //   {
        //     required: true,
        //     message: '账号不能为空！',
        //     trigger: ['blur']
        //   },
        //   {
        //     min: 2,
        //     max: 20,
        //     message: '账号长度为 2 到 20 个字符！',
        //     trigger: ['blur']
        //   },
        //   {
        //     validator: checkUsername,
        //     trigger: ['blur']
        //   }
        // ],
        nickname: [
          {
            min: 2,
            max: 20,
            message: '昵称长度为 2 到 20 个字符！',
            trigger: ['blur']
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱地址不能为空！',
            trigger: ['blur']
          },
          {
            type: 'email',
            message: '邮箱地址格式有误！',
            trigger: ['blur']
          }
        ],
        phone: [
          {
            pattern: /1[3-9][0-9]{9}/,
            message: '手机号码格式有误！',
            trigger: ['blur']
          },
          {
            max: 11,
            message: '手机号码格式有误！',
            trigger: ['blur']
          }
        ]
      },
      passwordDialogVisible: false,
      editPasswordForm: {
        old_password: '',
        new_password: '',
        key: ''
      },
      tmpOldPwd: '',
      tmpNewPwd: '',
      chars: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
      editPasswordRule: {
        old_password: [
          {
            required: true,
            message: '旧密码不能为空！',
            trigger: ['blur']
          },
          {
            min: 6,
            max: 20,
            message: '旧密码长度为 6 到 20 个字符！',
            trigger: ['blur']
          },
          {
            validator: checkOldPassword,
            trigger: ['blur']
          }
        ],
        new_password: [
          {
            required: true,
            message: '新密码不能为空！',
            trigger: ['blur']
          },
          {
            min: 6,
            max: 20,
            message: '新密码长度为 6 到 20 个字符！',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  methods: {
    // 打开个人信息对话框
    openUserInfoDialog () {
      this.userId = window.sessionStorage.getItem('id')
      getUserInfo(this.userId).then(response => {
        if (response.data.code !== 0) return this.$message.error('获取个人信息失败！')
        this.editUserForm = response.data.data
        if (this.editUserForm.is_superuser) {
          this.editUserForm.is_superuser = '管理员'
        } else {
          this.editUserForm.is_superuser = '普通用户'
        }
        this.userEmail = this.editUserForm.email
      })
      this.userDialogVisible = true
    },
    // 编辑用户
    editThisUser () {
      delete this.editUserForm.create_time
      delete this.editUserForm.is_superuser
      this.$refs.editUserRef.validate(valid => {
        if (!valid) return
        editUserInfo(this.userId, this.editUserForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('编辑用户信息失败！')
            this.$message.success('编辑用户信息成功！')
            this.userDialogCancelClose()
          })
      })
    },
    // 个人信息对话框默认关闭
    userDialogClose () {
      this.$refs.editUserRef.resetFields()
    },
    // 个人信息对话框关闭
    userDialogCancelClose () {
      this.userDialogVisible = false
    },
    // 打开修改密码对话框
    openPasswordDialog () {
      this.userId = window.sessionStorage.getItem('id')
      this.passwordDialogVisible = true
    },
    // 修改密码
    editPassword () {
      this.$refs.editPasswordRef.validate(valid => {
        if (valid) {
          for (let i = 0; i < 16; i++) {
            this.editPasswordForm.key += this.chars[Math.floor(Math.random() * this.chars.length)]
          }
          this.tmpOldPwd = this.editPasswordForm.old_password
          this.tmpNewPwd = this.editPasswordForm.new_password
          this.editPasswordForm.old_password = CryptoJS.AES.encrypt(
            CryptoJS.enc.Utf8.parse(this.editPasswordForm.old_password),
            CryptoJS.enc.Utf8.parse(this.editPasswordForm.key),
            { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString()
          this.editPasswordForm.new_password = CryptoJS.AES.encrypt(
            CryptoJS.enc.Utf8.parse(this.editPasswordForm.new_password),
            CryptoJS.enc.Utf8.parse(this.editPasswordForm.key),
            { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString()
          editUserPassword(this.userId, this.editPasswordForm)
            .then(response => {
              if (response.data.code !== 0) {
                this.editPasswordForm.old_password = this.tmpOldPwd
                this.editPasswordForm.new_password = this.tmpNewPwd
                this.editPasswordForm.key = ''
                return this.$message.error('修改密码失败！')
              }
              this.$message.success('修改密码成功！')
              this.passwordDialogCancelClose()
              this.editPasswordForm = {
                old_password: '',
                new_password: '',
                key: ''
              }
              this.$router.push('/login')
            })
        }
      })
    },
    // 修改密码对话框默认关闭
    passwordDialogClose () {
      this.$refs.editPasswordRef.resetFields()
    },
    // 修改密码对话框关闭
    passwordDialogCancelClose () {
      this.passwordDialogVisible = false
    },
    // 登出
    userLogout () {
      this.$router.push('/login')
    },
    // 获取导航菜单
    async getNavList () {
      getNavs()
        .then(response => {
          if (response.data.code !== 0) return
          this.navList = response.data.data
        })
    }
  }
}
</script>

<style lang="less" scoped>
  /*全局背景*/
  .content {
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    position: fixed;
  }

  .contain {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    display: flex;
  }

  .outer {
    width: 94%;
    height: 92%;
    margin: 2%;
    align-self: center;
  }

  /*左侧*/
  .el-aside {
    margin-right: 1.5%;
    border-radius: 10px;
    border: 1px solid rgb(0, 0, 0);
    background: rgba(255, 255, 255, 1);
  }

  .platform {
    width: 100%;
    height: 60px;
    font-size: 20px;
    padding-top: 30px;
    text-align: center;

    span {
      font-size: 14px;
      padding-left: 180px;
    }
  }

  .el-menu {
    border-right: none;
  }

  .el-submenu {
    .el-menu-item {
      margin-left: 10px;
    }
  }

  /*顶部*/
  .el-header {
    margin-bottom: 1.5%;
    border-radius: 10px;
    border: 1px solid rgb(0, 0, 0);
    background: rgba(255, 255, 255, 1);
    display: flex;
  }

  .el-dropdown {
    align-self: center;
    margin-left: auto;
    border-radius: 3px;
  }
  /deep/ .el-button-group>.el-button {
    border: 1px solid dimgrey;
  }
  .el-dropdown-link {
    color: #000000;
  }
  /*内容主体*/
  .el-main {
    border-radius: 10px;
    border: 1px solid rgb(0, 0, 0);
    background: rgba(255, 255, 255, 1);
  }
  /deep/ .el-dialog__body {
    padding: 20px 35px 10px 20px;
  }
</style>
